import urllib.request
import urllib.parse
from http.client import HTTPConnection
from http.client import HTTPResponse


class httphand():
	def geturl(self, url):
		resp = self.run(url)
		if not hasattr(resp, 'status'):
			result = self.runurl(url)
			pass
		else:
			try:
				tt = []
				while resp.status != 200:
					tt.append(resp.getheader('location'))
					if resp.getheader('location') in tt:
						break
					tmp = {}
					tmp['status'] = resp.status
					resp = self.run(resp.getheader('location'))
				data = resp.read().decode('utf-8')
				response = resp.status
				result = {'data':data, 'response':response}
			except:
				print("$$$")
				result = self.runrul(url)
		return result

	def runurl(self, url):
		try:
			aaa = urllib.request.urlopen(url, tmieout=7)
			data = aaa.read().decode('utf-8')
			response = aaa.getcode()
			return {'data':data, 'response':response}
		except:
			return None

	def run(self, url):
		resp = None
		try:
			host = urllib.parse.urlparse(url)[1]
			req = '/'
			conn = httplib.HTTPConnection(host, timeout = 10)
			headers = {'User-Agent':'Mozilla/5.0 (X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0'}
			conn.request('GET', req, headers = headers)
			resp = conn.getresponse()
		except:
			pass
		return resp